package dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Persistence;

import model.EntidadeAbstrata;



@SuppressWarnings("unchecked")
public class DaoGenerico<T extends EntidadeAbstrata> {

	
	
	protected static EntityManager entityManager;

	static {
		EntityManagerFactory entityFabrica = Persistence.createEntityManagerFactory("ComaBemLanchonete");
		entityManager = entityFabrica.createEntityManager();
	}

	
	
	public T getById(int id) {
		return (T) entityManager.find(getTypeClass(), id);
	}

	public void salvar(T entidade) {
		try {
			entityManager.getTransaction().begin();
			entityManager.persist(entidade);
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			entityManager.getTransaction().rollback();
		}
	}

	public void atualizar(T entidade) {
		try {
			entityManager.getTransaction().begin();
			entityManager.merge(entidade);
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			entityManager.getTransaction().rollback();
		}
	}

	public void delete(T entidade) {
		try {
			entityManager.getTransaction().begin();
			entityManager.remove(entidade);
			entityManager.getTransaction().commit();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			entityManager.getTransaction().rollback();
		}
	}

	public List<T> buscaTodos() {
		return entityManager.createQuery(("From " + getTypeClass().getName()))
				.getResultList();
	}

	private Class<?> getTypeClass() {
		// TODO Auto-generated method stub
		Class<?> classes = (Class<?>) ((ParameterizedType) this.getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];

		return classes;
	}
}
